<template>
  <view class="verify-bg">
    <view class="verify-card">
      <view class="upload-block">
        <view class="tip">上传身份证正面</view>
        <view class="upload-area" @click="upload('front')">
          <image v-if="idCardFront" class="uploaded-image" :src="idCardFront" mode="aspectFit" />
          <template v-else>
            <image class="upload-icon" src="/static/up-photo.png" />
            <view class="upload-tip">点击上传</view>
          </template>
        </view>
      </view>
      <view class="upload-block">
        <view class="tip">上传身份证反面</view>
        <view class="upload-area" @click="upload('back')">
          <image v-if="idCardBack" class="uploaded-image" :src="idCardBack" mode="aspectFit" />
          <template v-else>
            <image class="upload-icon" src="/static/up-photo.png" />
            <view class="upload-tip">点击上传</view>
          </template>
        </view>
      </view>
      <view class="info-card">
        <view class="row">
          <view class="label">姓名</view>
          <view class="val" :class="{ muted: !realName }">{{ realName || '请上传身份证正面识别' }}</view>
        </view>
        <view class="row">
          <view class="label">身份证号</view>
          <view class="val" :class="{ muted: !idCardNumber }">{{ idCardNumber || '请上传身份证正面识别' }}</view>
        </view>
        <view class="row">
          <view class="label">你的年龄</view>
          <view class="val" :class="{ muted: !age }">{{ age ? age + '岁' : '请上传身份证正面识别' }}</view>
        </view>
      </view>
    </view>
    <button class="submit-btn" @click="handleSubmit">提交</button>
  </view>
</template>

<script setup>
  import { ref } from 'vue';
  import { baseUrl, apiPath, tenantId } from '@/sheep/config';
  import { getAccessToken } from '@/sheep/request';
  import UserApi from '@/sheep/api/member/user';
  import FileApi from '@/sheep/api/infra/file';

  const idCardFront = ref('');
  const idCardBack = ref('');
  const idCardFrontUrl = ref(''); // 身份证正面图片URL
  const idCardBackUrl = ref(''); // 身份证反面图片URL
  const idCardNumber = ref('');
  const age = ref('');
  const realName = ref('');

  // 根据出生日期计算年龄
  function calculateAge(birthDate) {
    if (!birthDate) return null;
    
    try {
      // 处理 "1990年1月19日" 格式
      let year, month, day;
      const match = birthDate.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
      if (match) {
        year = parseInt(match[1]);
        month = parseInt(match[2]);
        day = parseInt(match[3]);
      } else {
        // 尝试其他日期格式
        const date = new Date(birthDate);
        if (isNaN(date.getTime())) return null;
        year = date.getFullYear();
        month = date.getMonth() + 1;
        day = date.getDate();
      }
      
      const today = new Date();
      const currentYear = today.getFullYear();
      const currentMonth = today.getMonth() + 1;
      const currentDay = today.getDate();
      
      let age = currentYear - year;
      // 如果还没到生日，年龄减1
      if (currentMonth < month || (currentMonth === month && currentDay < day)) {
        age--;
      }
      
      return age > 0 ? age : null;
    } catch (error) {
      console.error('计算年龄失败:', error);
      return null;
    }
  }

  // 上传图片获取URL
  async function uploadImageToGetUrl(filePath, side) {
    try {
      const uploadRes = await FileApi.uploadFile(filePath, 'id-card');
      if (uploadRes && uploadRes.data) {
        const imageUrl = typeof uploadRes.data === 'string' ? uploadRes.data : (uploadRes.data.url || uploadRes.data);
        if (side === 'front') {
          idCardFrontUrl.value = imageUrl;
        } else {
          idCardBackUrl.value = imageUrl;
        }
        return imageUrl;
      }
    } catch (error) {
      console.error('上传图片失败:', error);
    }
    return null;
  }

  // 识别身份证（仅正面）
  function recognizeIdCard(filePath) {
    return new Promise((resolve, reject) => {
      uni.showLoading({ title: '识别中...' });
      
      uni.uploadFile({
        url: baseUrl + apiPath + '/member/app/id-card/recognize',
        filePath: filePath,
        name: 'image',
        formData: { side: 'front' },
        header: {
          Accept: '*/*',
          'tenant-id': tenantId,
          Authorization: 'Bearer ' + getAccessToken(),
        },
        success: (uploadRes) => {
          uni.hideLoading();
          try {
            const result = JSON.parse(uploadRes.data);
            if (result && result.code === 0 && result.data) {
              // 填充识别结果
              if (result.data.name) realName.value = result.data.name;
              if (result.data.idNumber) idCardNumber.value = result.data.idNumber;
              if (result.data.age) {
                age.value = result.data.age;
              } else if (result.data.birth) {
                const calculatedAge = calculateAge(result.data.birth);
                if (calculatedAge !== null) age.value = calculatedAge;
              }
              resolve(result);
            } else {
              uni.showToast({ title: result?.msg || '识别失败', icon: 'none' });
              reject(result);
            }
          } catch (error) {
            console.error('解析响应失败:', error);
            uni.showToast({ title: '识别失败', icon: 'none' });
            reject(error);
          }
        },
        fail: (error) => {
          uni.hideLoading();
          console.error('识别失败:', error);
          uni.showToast({ title: '识别失败，请重试', icon: 'none' });
          reject(error);
        }
      });
    });
  }

  async function upload(which) {
    uni.showActionSheet({
      itemList: ['拍照', '从相册选择'],
      success: async (res) => {
        const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];
        
        uni.chooseImage({
          count: 1,
          sourceType: sourceType,
          sizeType: ['compressed'],
          success: async (chooseRes) => {
            try {
              const filePath = chooseRes.tempFilePaths[0];
              
              // 先上传图片获取URL
              uni.showLoading({ title: '上传中...' });
              const imageUrl = await uploadImageToGetUrl(filePath, which);
              uni.hideLoading();
              
              if (!imageUrl) {
                uni.showToast({ title: '上传失败，请重试', icon: 'none' });
                return;
              }
              
              // 保存显示用的图片
              if (which === 'front') {
                idCardFront.value = filePath;
                // 如果是正面，调用识别接口
                await recognizeIdCard(filePath);
              } else {
                idCardBack.value = filePath;
              }
            } catch (error) {
              console.error('处理失败:', error);
            }
          },
          fail: (err) => {
            if (!err.errMsg?.includes('cancel')) {
              uni.showToast({ title: '选择图片失败', icon: 'none' });
            }
          }
        });
      }
    });
  }

  // 提交实名认证
  async function handleSubmit() {
    if (!idCardFrontUrl.value || !idCardBackUrl.value) {
      uni.showToast({ title: '请上传身份证正反面', icon: 'none' });
      return;
    }
    if (!realName.value || !idCardNumber.value || !age.value) {
      uni.showToast({ title: '请上传身份证正面以识别信息', icon: 'none' });
      return;
    }

    try {
      const res = await UserApi.realnameAuth({
        realName: realName.value,
        idCardNumber: idCardNumber.value,
        age: Number(age.value),
        cardFront: idCardFrontUrl.value,
        cardBack: idCardBackUrl.value
      });

      if (res && res.code === 0) {
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('提交实名认证失败:', error);
    }
  }
</script>

<style lang="scss" scoped>
.verify-bg {
  min-height: 100vh;
  background: #f7f7fa;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.verify-card {
  width: 100%;
  padding: 35rpx 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.upload-block {
  background: #fff;
  border-radius: 26rpx;
  width: 97vw;
  max-width: 710rpx;
  margin-bottom: 28rpx;
  padding: 0 0 36rpx 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.tip {
  margin: 32rpx 0 22rpx 32rpx;
  font-size: 31rpx;
  font-weight: 500;
  color: #222;
}
.upload-area {
  background: #f6f6f7;
  border-radius: 16rpx;
  width: 90vw;
  max-width: 650rpx;
  height: 410rpx;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}
.upload-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 16rpx;
  opacity: 0.55;
}
.upload-tip {
  color: #666;
  font-size: 26rpx;
}
.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-card {
  background: #fff;
  border-radius: 22rpx;
  width: 97vw;
  max-width: 710rpx;
  padding: 22rpx 0 16rpx 0;
  margin: 18rpx 0 0 0;
  display: flex;
  flex-direction: column;
}
.row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 33rpx 22rpx 33rpx;
  font-size: 30rpx;
}
.label {
  color: #222;
}
.val {
  min-width: 140rpx;
  text-align: right;
  color: #222;
}
.val.muted {
  color: #b0b3be;
}
.submit-btn {
  width: 85%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 56rpx;
  color: #fff;
  font-size: 30rpx;
  background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 66rpx auto 0;
}
</style>
